$(function(){
	//加载部门列表
	$('#department').fileTree({
		root: 'source',
		script: 'sysDepartmentAction!queryDepartmentAll.ac',
		expandEasing: 'easeOutBounce',
		collapseEasing: 'easeOutBounce',
		expandAll: false,
		showLeaf: false,
		showCheckbox: true,
		complete:function(){
			//只有一个checkbox可被选中
			var $c = $('#department :checkbox');
			$c.click(function(){
				$c.removeAttr('checked');
				$(this).attr('checked','true');
			});
			
			//加载角色列表
			$('#role').fileTree({
				root: 'source',
				script: 'sysRoleAction!queryRoleAll.ac',
				expandEasing: 'easeOutBounce',
				collapseEasing: 'easeOutBounce',
				expandAll: false,
				showLeaf: false,
				showCheckbox: true,
				onlyOneCanChecked: false
			});
		}
	});
	
	//提交事件
	$('#submitBtn').click(function(){
		var $n = $('#sysUserName');
		var $p = $('#sysUserPassword');
		var $f = $('#confirmPassword');
		var $e = $('#sysUserEmail');
		var $d = $('#department :checkbox[checked]');
		var $r = $('#role :checkbox[checked]');
		
		if($n.val() == ''){
			jAlert('名称必填');
			return;
		}else if(!Validator.username($n.val())){
			jAlert('名称，以字母开关，3-20位');
			return;
		}
		
		if($p.val() == ''){
			jAlert('密码必填');
			return;
		}else if(!Validator.password($p.val())){
			jAlert('密码，以字母或数字开头，6-20位');
			return;
		}
		
		if($f.val() == ''){
			jAlert('确认密码必填');
			return;
		}else if(!Validator.password($f.val())){
			jAlert('确认密码，以字母或数据开头，6-20位');
			return;
		}
		
		if($p.val() != $f.val()){
			jAlert('密码与确认密码不一致');
			return;
		}
		
		if($e.val() == ''){
			jAlert('邮箱必填');
			return;
		}else if(!Validator.isEmail($e.val())){
			jAlert('邮箱格式不正确');
			return;
		}
		
		if($d.size() != 1){
			jAlert('必须且只能选择一个所属部门');
			return;
		}
		
		$p.val($.md5($p.val()));
		$f.val($.md5($f.val()));
		
		function collectData(){
			var a = new Array();
			a.push('sysUser.name=' + $n.val());
			a.push('sysUser.password=' + $p.val());
			a.push('sysUser.email=' + $e.val());
			a.push('sysUser.departmentId=' + $d.val());
			
			var b = new Array();
			if($r.size() > 0){
				$r.each(function(){
					b.push($(this).val());
				});
				a.push('roles=' + b.join(','));
			}
			
			return a.join('&');
		}
		
		$.ajax({
			type:'POST',
			url: 'sysUserAction!addUser.ac',
			data: collectData(),
			dataType:'json',
			beforeSend:function(){
				jLoading("正在操作，请稍后...");
			},
			success:function(rs){
				if(rs.flag){
					jAlert('操作成功');
				}else{
					jAlert('操作失败:' + rs.msg);
				}
			}
		});
	});
});